//
//  MianWindowController.swift
//  MacStudy
//
//  Created by 30san on 2020/11/18.
//  Copyright © 2020 Dawninest. All rights reserved.
//

import Cocoa

class MianWindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()
        
        let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
        let vc = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier.init("ViewController")) as! NSViewController
        // 设置内容控制器
        self.contentViewController = vc
        
        // 设置颜色
        self.window?.backgroundColor = NSColor.red
        // window 设置模式
//        self.window?.appearance = NSAppearance(named: .darkAqua)
        // window 标题
        self.window?.title = "macDemo"
        
        // window保持居中显示,不记录上一次的位置
        self.window?.isRestorable = false
        
        // 设置大小  同样需要 self.window?.isRestorable = false
        self.window?.setFrame(NSRect(x: 0, y: 0, width: 700, height: 500), display: true)
        
        self.window?.center()
        
        
        
        // 设置window toolbar和左上角 关闭、缩小在同一行
//        self.window?.titleVisibility = .hidden
    }
    
    // 保存文件
    @IBAction func saveFiles(_ sender: NSToolbarItem) {
        let dataDic = ["name": "张三", "age": "20"]
        do {
            let data = try JSONSerialization.data(withJSONObject: dataDic, options: JSONSerialization.WritingOptions.fragmentsAllowed)
            let savePanel = NSSavePanel()
            savePanel.allowedFileTypes = ["txt"]
            savePanel.showsTagField = false
            let ret = savePanel.runModal()
            if ret == .OK {
                let url = savePanel.url!
//                try data.write(to: url)
                print("url = \(url)")
            }
        } catch {
            
        }
    }
    
    @IBAction func clickOpen(_ sender: NSToolbarItem) {
        print("clickOpen")
        // 选择文件的功能
        let openPanel = NSOpenPanel()
        openPanel.canChooseFiles = true
        openPanel.canCreateDirectories = true
        openPanel.canChooseDirectories = true
        openPanel.allowsMultipleSelection = true
        let ret = openPanel.runModal()
        if ret == .OK {
            print("选择的文件路径 path = \(openPanel.urls)")
        }
    }
    
}
